    //
//  MultipleChoicePageViewController.m
//  ActiveDeck
//
//  Created by Chiao-Wei Liu on 2011/2/15.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PageViewController.h"
#import "MultipleChoicePageViewController.h"
#import "AD_Page.h"
#import "AD_Button.h"

int selectedAnswer;

@implementation MultipleChoicePageViewController
@synthesize BG_Image,buttonSets, Bt_Submit;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

- (GDataXMLElement *)BuildXmlData{
	GDataXMLElement *answerElement = [GDataXMLElement elementWithName:@"Answer"];
	GDataXMLNode *Type = [GDataXMLNode attributeWithName:@"Type" stringValue:@"MultipleChoice"];
	GDataXMLNode *Page = [GDataXMLNode attributeWithName:@"Page" stringValue:[NSString stringWithFormat:@"%d",pageOB.pageID]];
	GDataXMLNode *Value = [GDataXMLNode attributeWithName:@"Value" stringValue:[NSString stringWithFormat:@"%d", selectedAnswer]];
	[answerElement addChild:Type];
	[answerElement addChild:Page];
	[answerElement addChild:Value];
	
	return answerElement;	
}



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    BG_Image.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:pageOB.imageBG]];

    [self addImage];

	//NSLog(@"Loading MultipleChoiceView");
	buttonSets = [[NSMutableArray alloc]init];
	[self AddButton];
    
    [super viewDidLoad];

}

- (void)AddButton{
	
    int i=0;
	for(AD_Button *multiButton in pageOB.mut_Arr_Button)
	{
		UIImage *offImage = [UIImage imageWithData:[NSData dataWithContentsOfFile:multiButton.imageOff]];
		UIImage *onImage = [UIImage imageWithData:[NSData dataWithContentsOfFile:multiButton.imageOn]];
		CGRect buttonFrame = CGRectMake(multiButton.left, multiButton.top, multiButton.width, multiButton.height);
		NSArray *condition = [multiButton.Condition componentsSeparatedByString:@"=="];
        
		UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
		[newButton setFrame:buttonFrame];
		[newButton setTag:i++];
		[newButton setBackgroundImage:offImage forState:UIControlStateNormal];
		[newButton setBackgroundImage:onImage forState:UIControlStateHighlighted];
		[newButton setBackgroundImage:onImage forState:UIControlStateSelected];
		[newButton addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];
		
        for(AD_Action *action in multiButton.actions){
            if([action.type isEqualToString:@"Submit"] || [action.type isEqualToString:@"Next"])
            {
                newButton.enabled = NO;
                Bt_Submit = newButton;
                break;
            }
        }
        
        [newButton setHidden:[self setCondition:condition]];
		
		[buttonSets addObject:newButton]; //Test memory location 
		[self.view	addSubview:newButton]; //Test memory removed
	}
}

-(void)buttonPress:(id)sender
{
	UIButton *pressButton = (UIButton *)sender;
	AD_Button *multiButton = (AD_Button*)[pageOB.mut_Arr_Button objectAtIndex:pressButton.tag];
	
	//NSLog(@"Button Type %@", multiButton.buttonType);
    
    for(AD_Action *action in multiButton.actions){
        if([action isKindOfClass:[Action_Toggle class]]){
            selectedAnswer = ((Action_Toggle*)action).value;
            pressButton.selected = YES;
            if(Bt_Submit != NULL)
                Bt_Submit.enabled = YES;
            
            for(UIButton *otherButton in buttonSets)
            {
                NSLog(@"buttonSetsCount:%d", [buttonSets count]);
                
                if(otherButton.tag != pressButton.tag)
                    otherButton.selected = NO;
            }
        } else if([action isKindOfClass:[Action_Submit class]]){
            [self appendUserData:[self BuildXmlData]];
            [self submitUserData];
            NSLog(@"Submit the user data");
            Bt_Submit.enabled = NO;
            
            //Disable Multiple choice buttons
            int i =0;
            for(UIButton *otherButton in buttonSets)
            {
                if(i++ != pressButton.tag)
                    otherButton.enabled = NO;
            }
        }else if ([action isKindOfClass:[Action_Next class]]) {
            NSLog(@"Go to the next page");
            [self appendUserData:[self BuildXmlData]];
            if(pageOB.grade.hasInstantFeedback)
            {
                [self addInstantFeedback];
            } else {        
                [self loadNextPage];
            }
        }else if ([action isKindOfClass:[Action_GoTo class]]) {
            Action_GoTo *gt = (Action_GoTo*)action;
            NSLog(@"Go To Special Session");
            [self appendUserData:[self BuildXmlData]];
            [self GoToSection:gt.section
                    NewPageID:gt.page];
        }else if ([action isKindOfClass:[Action_Save class]]){
            NSLog(@"Save Button Pressed");
            
            NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
            NSString *ACTIVEDECKSAVEKEY = [NSString stringWithFormat:@"Value(%d)", pageOB.pageID];
            
            [prefs setObject:[NSString stringWithFormat:@"%d", selectedAnswer] forKey:ACTIVEDECKSAVEKEY];
            NSLog(@"Value(%d) saved", pageOB.pageID);
            
            NSString *ACTIVEDECKKIOSK = @"Kiosk";
            [prefs setObject:[NSString stringWithFormat:@"%d", selectedAnswer] forKey:ACTIVEDECKKIOSK];
            
            
            [_delegate updateSecondaryChannelID:selectedAnswer];
            
            [prefs synchronize];
            [self loadNextPage];
            
        }

    }
	
//	if([multiButton.buttonType isEqualToString:@"Toggle"])
//	{
//		selectedAnswer = multiButton.value;
//		pressButton.selected = YES;
//        if(Bt_Submit != NULL)
//            Bt_Submit.enabled = YES;
//		
//		for(UIButton *otherButton in buttonSets)
//		{
//            NSLog(@"buttonSetsCount:%d", [buttonSets count]);
//
//			if(otherButton.tag != pressButton.tag)
//				otherButton.selected = NO;
//		}
//		
//	}else if ([multiButton.buttonType isEqualToString:@"Submit"]) {
//		[self appendUserData:[self BuildXmlData]];
//		[self submitUserData];
//		NSLog(@"Submit the user data");
//		Bt_Submit.enabled = NO;
//		
//		//Disable Multiple choice buttons
//		int i =0;
//		for(UIButton *otherButton in buttonSets)
//		{
//			if(i++ != pressButton.tag)
//				otherButton.enabled = NO;
//		}
//        
//	}else if ([multiButton.buttonType isEqualToString:@"Next"]) {
//		NSLog(@"Go to the next page");
//		[self appendUserData:[self BuildXmlData]];
//        if(pageOB.grade.hasInstantFeedback)
//        {
//            [self addInstantFeedback];
//        } else {        
//            [self loadNextPage];
//        }
//	}else if ([multiButton.buttonType isEqualToString:@"GoTo"]) {
//        NSLog(@"Go To Special Session");
//        [self appendUserData:[self BuildXmlData]];
//        [self GoToSection:multiButton.section
//                NewPageID:multiButton.page];
//    }else if ([multiButton.buttonType isEqualToString:@"Save"]){
//        NSLog(@"Save Button Pressed");
//        
//        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
//        NSString *ACTIVEDECKSAVEKEY = [NSString stringWithFormat:@"Value(%d)", pageOB.pageID];
//        
//        [prefs setObject:[NSString stringWithFormat:@"%d", selectedAnswer] forKey:ACTIVEDECKSAVEKEY];
//        NSLog(@"Value(%d) saved", pageOB.pageID);
//        
//        [prefs synchronize];
//        [self loadNextPage];
//
//    }
}
							   



- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [BG_Image release];
    [buttonSets release];
    [super dealloc];

}


@end
